package com.leyou.gateway.filters;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 刷新redis的JTI有效期
 *
 * @author 虎哥
 */
@Slf4j
@Component
public class TokenRefreshFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            // 获取request
            ServerHttpRequest request = exchange.getRequest();
            // 获取cookie中的JWT
            MultiValueMap<String, HttpCookie> cookies = request.getCookies();
            HttpCookie httpCookie = cookies.getFirst(JwtConstants.COOKIE_NAME);
            if (httpCookie == null) {
                // 未登录，放行
                return chain.filter(exchange);
            }
            String jwt = httpCookie.getValue();
            // 刷新redis中的JTI的有效期
            jwtUtils.refreshJwt(jwt);
        } catch (Exception e) {
            log.warn("刷新用户token异常。{}", e.getMessage());
        }
        // 放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
